package other.xsy.passlys;

import com.rkhd.platform.sdk.data.model.Opportunity;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import other.xsy.passlys.util.HCXObjectService;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @Author: 黎炎松
 * @Date: 2024/4/12 15:28
 */
public class OpportunityUpdateTimeTrigger implements Trigger {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "修改销售机会签约预测，更新修改时间 ==> ";

    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.debug(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<Opportunity> opportunitiesList = new ArrayList<>();
        for (XObject xObject : dataList) {
            Opportunity opportunity = (Opportunity) xObject;
            opportunitiesList.add(opportunity);
            dataResultList.add(new DataResult(true, "", xObject));
        }
        updateTimeByCommit(opportunitiesList.get(0));
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    /**
     * 修改签约预测更新时间
     * @param opportunity
     */
    public void updateTimeByCommit (Opportunity opportunity){
        try {
            logger.debug(LOGGER_MSG + " 处理开始");

            // 签约预测修改前
            Opportunity oldOpportunity = new Opportunity();
            oldOpportunity.setId(opportunity.getId());
            oldOpportunity = hcxObjectService.get(oldOpportunity);

            if (oldOpportunity.getContractPrediction__c() == null || opportunity.getContractPrediction__c() == null) {
                return;
            }

            Integer oldCommit = oldOpportunity.getContractPrediction__c();

            // 签约预测修改后
            Integer newCommit = opportunity.getContractPrediction__c();

            /*
                比较 如果修改前为 commit 修改后不是 commit  更新时间
                commit 1
                upside 2
                无     3
             */
            logger.debug(LOGGER_MSG + "签约预测修改前: " + oldOpportunity);
            logger.debug(LOGGER_MSG + "签约预测修改后: " + newCommit);
            if (oldCommit == 1 && newCommit != 1) {
                opportunity.setNoncommitDate__c(System.currentTimeMillis());
            }

        } catch (ApiEntityServiceException e) {
            logger.debug(LOGGER_MSG + " 处理异常");
        }
    }

}
